import React, { useState, useEffect } from 'react';
import { View, Text, Button, Image } from '@tarojs/components';
import { Circle, Progress } from "@taroify/core"
import PageContainer from '@/components/PageContainer';
import templateService from '@/templates/templateService';
import Taro from '@tarojs/taro';
import './index.scss';
import { confirmDeviceOtaTask, getAiDeviceVersion, getDeviceOtaTask, pushDeviceOtaTask } from '@/services/ai';

// OTA 更新状态枚举
enum OtaStatus {
  CHECKING = 'CHECKING',     // 检查更新中
  LATEST = 'LATEST',        // 已是最新版本
  UPDATE_AVAILABLE = 'UPDATE_AVAILABLE', // 有可用更新
  UPDATING = 'UPDATING',    // 更新中
  UPDATE_SUCCESS = 'UPDATE_SUCCESS',     // 更新成功
}

interface OtaInfo {
  status: OtaStatus;
  progress: number;
  startTime: number;
  taskId: string;
  targetVersion: string;
}

const OTA_STORAGE_KEY = 'ota_status_info';
const OTA_TIMEOUT = 5 * 60 * 1000; // 5分钟超时
const PROGRESS_INTERVAL = 1000; // 1秒更新一次进度

const OtaPage = () => {
  const [status, setStatus] = useState<OtaStatus>(OtaStatus.CHECKING);
  const [currentVersion, setCurrentVersion] = useState('');
  const [newVersion, setNewVersion] = useState('');
  const [progress, setProgress] = useState(10);
  const [taskId, setTaskId] = useState('');
  const [taskStatus, setTaskStatus] = useState(0);
  const [progressTimer, setProgressTimer] = useState<NodeJS.Timer | null>(null);
  const deviceId = Taro.getCurrentInstance().router?.params.id || '';

  // 从本地存储加载OTA状态
  const loadOtaStatus = () => {
    const savedInfo = Taro.getStorageSync(OTA_STORAGE_KEY) as OtaInfo | null;
    if (savedInfo) {
      const now = Date.now();
      if (now - savedInfo.startTime > OTA_TIMEOUT) {
        // 超时，清除状态
        Taro.removeStorageSync(OTA_STORAGE_KEY);
        return null;
      }
      return savedInfo;
    }
    return null;
  };

  // 保存OTA状态到本地存储
  const saveOtaStatus = (info: OtaInfo) => {
    Taro.setStorageSync(OTA_STORAGE_KEY, info);
  };

  // 清除OTA状态
  const clearOtaStatus = () => {
    Taro.removeStorageSync(OTA_STORAGE_KEY);
    if (progressTimer) {
      clearInterval(progressTimer);
      setProgressTimer(null);
    }
  };

  // 检查设备版本
  const checkDeviceVersion = async () => {
    const versionInfo = await getAiDeviceVersion({ id: deviceId || '' });
    console.log('versionInfoversionInfo', versionInfo)
    if (versionInfo.success) {
      setCurrentVersion(versionInfo.data.soft_version);
      return versionInfo.data.soft_version;
    }
    return null;
  };

  // 检查可用更新
  const checkAvailableUpdates = async () => {
    console.log('checkAvailableUpdates')
    const result = await getDeviceOtaTask(deviceId);
    console.log('checkAvailableUpdates', result)
    if (result.success && result.data?.data?.length > 0) {
      let update = null 
      result.data.data.map(item => {
        if (item.firmware_version > currentVersion) {
          setNewVersion(item.firmware_version);
          setTaskId(item.id);
          setTaskStatus(item.status);
          update = item;
        }
      })
      return update;
    }
    return null;
  };

  // 开始进度更新
  const startProgressUpdate = (startProgress: number) => {
    if (progressTimer) {
      clearInterval(progressTimer);
    }

    const timer = setInterval(() => {
      setProgress(prev => {
        const next = prev + 1;
        if (next >= 90) {
          clearInterval(timer);
          setProgressTimer(null);
          return 90;
        }
        
        // 更新本地存储中的进度
        const savedInfo = Taro.getStorageSync(OTA_STORAGE_KEY) as OtaInfo | null;
        if (savedInfo) {
          const updatedInfo = {
            ...savedInfo,
            progress: next
          };
          Taro.setStorageSync(OTA_STORAGE_KEY, updatedInfo);
        }
        
        return next;
      });
    }, PROGRESS_INTERVAL);

    setProgressTimer(timer);
    setProgress(startProgress);
  };

  // 开始更新
  const handleUpdate = async () => {
    try {
      Taro.showLoading({
        title: ''
      })
      let confirmResult = {success: true}
      if (taskStatus === 3) {
        confirmResult = await confirmDeviceOtaTask(deviceId, taskId)
      }
      if (confirmResult.success) {
        const result = await pushDeviceOtaTask(deviceId, taskId);
        if (result.success) {
          setStatus(OtaStatus.UPDATING);
          const otaInfo: OtaInfo = {
            status: OtaStatus.UPDATING,
            progress: 0,
            startTime: Date.now(),
            taskId,
            targetVersion: newVersion
          };
          saveOtaStatus(otaInfo);
          startProgressUpdate(10);
        } else {
          Taro.showToast({
            title: '推送OTA失败',
            icon: 'none'
          })
        }
        Taro.hideLoading();
      } else {
        Taro.hideLoading();
        Taro.showToast({
          title: '确认OTA失败',
          icon: 'none'
        })
      }
      
    } catch (error) {
      Taro.showToast({
        title: 'OTA失败',
        icon: 'none'
      })
    }
  };

  // 检查更新状态
  const checkUpdateStatus = async () => {
    const version = await checkDeviceVersion();
    console.log('versionversionversion', version)
    if (!version) return;

    const savedInfo = loadOtaStatus();
    if (savedInfo && savedInfo.status === OtaStatus.UPDATING) {
      if (version === savedInfo.targetVersion) {
        // 更新成功
        setStatus(OtaStatus.UPDATE_SUCCESS);
        clearOtaStatus();
      } else {
        // 继续更新
        setStatus(OtaStatus.UPDATING);
        setNewVersion(savedInfo.targetVersion);
        setTaskId(savedInfo.taskId);
        startProgressUpdate(savedInfo.progress);
      }
    } else {
      // 检查是否有可用更新
      const update = await checkAvailableUpdates();
      console.log('checkAvailableUpdates', update)
      if (update) {
        setStatus(OtaStatus.UPDATE_AVAILABLE);
      } else {
        setStatus(OtaStatus.LATEST);
      }
    }
  };

  useEffect(() => {
    checkUpdateStatus();

    return () => {
      if (progressTimer) {
        clearInterval(progressTimer);
      }
    };
  }, []);

  const renderContent = () => {
    switch (status) {
      case OtaStatus.CHECKING:
        return (
          <View className='status-container'>
            <Text className='status-text'>检查更新中...</Text>
          </View>
        );

      case OtaStatus.LATEST:
        return (
          <View className='status-container'>
            <Text className='version-text'>当前版本：{currentVersion}</Text>
            <Image className='status-image' src='https://xbgroup-static.gizwits.com/cybertron/users/391941/media/drawkit-grape-pack-illustration-7_1743147810295.png'></Image>
            <Text className='status-text'>已是最新版本</Text>
          </View>
        );

      case OtaStatus.UPDATE_AVAILABLE:
        return (
          <View className='status-container'>
            <Text className='version-text'>当前版本：{currentVersion}</Text>
            <Text className='version-text'>最新版本：{newVersion}</Text>
            <Image className='status-image' src='https://xbgroup-static.gizwits.com/cybertron/users/391941/media/drawkit-grape-pack-illustration-2_1743148260174.png'></Image>
            <Button className='update-button' onClick={handleUpdate}>
              开始更新
            </Button>
          </View>
        );

      case OtaStatus.UPDATING:
        return (
          <View className='status-container'>
            <Text className='status-text'>更新中...</Text>
            <Text className='version-text'>当前版本：{currentVersion}</Text>
            <Text className='version-text'>目标版本：{newVersion}</Text>
            <View className='circle-container'>
              <Progress style={{width: '100%'}} percent={progress} />
              {/* <Circle 
                percent={progress}
                size={170}
                strokeWidth={30}
                color={"#1890ff"}
                layerColor="#ebedf0"
              >
                <View className='circle-content'>
                  <Text className='circle-text'>{progress}%</Text>
                </View>
              </Circle> */}
            </View>
            <View style={{height: 100}}></View>
          </View>
        );

      case OtaStatus.UPDATE_SUCCESS:
        return (
          <View className='status-container'>
            <Text className='status-text'>更新成功！</Text>
            <Text className='version-text'>当前版本：{newVersion}</Text>
            <Image className='status-image' src='https://xbgroup-static.gizwits.com/cybertron/users/391941/media/drawkit-grape-pack-illustration-14_1743148374796.png'></Image>
          </View>
        );


      default:
        return null;
    }
  };

  return (
    <PageContainer safeArea={false} title="OTA 更新">
      <View className='ota-container'>
        {renderContent()}
      </View>
    </PageContainer>
  );
};

export default OtaPage;